﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElingOA6_Admin_DSJCJ.Common;
using DevExpress.Web.Mvc;
using System.Data;
using ElingOA6_Admin_DSJCJ.Models;
using System.Text;
using Newtonsoft.Json;

namespace ElingOA6_Admin_DSJCJ.Areas.Admin.Controllers
{
    /// <summary>
    /// 用品采购申请
    /// </summary>
    /// 
    [OutputCache(Duration = 0, VaryByParam = "none")]
    public class OfficeItemPurchaseApplyController : AdminBaseController
    {
        //
        // GET: /Admin/OfficeItemPurchaseApply/      
        /// <summary>
        /// 用品采购申请主页
        /// </summary>
        /// <returns>视图</returns>
        [AuthorityActionFilter("m_OfficeItemPurchaseApply", Order = 1)]
        [LogPageActionFilter("用品采购申请", Order = 2)]
        public ActionResult Index()
        {
            return View();
        }


        /// <summary>
        /// 列表
        /// </summary>
        /// <returns>视图</returns>
        public ActionResult OfficeItemPurchaseApplyList() {

            int pageIndex = 1;
            List<Model.ItemPurchaseApply> itemPurchaseApplyList = GetItemPurchaseApplyList(pageIndex);

            return View(itemPurchaseApplyList);

        }


        /// <summary>
        /// 用于刷新
        /// </summary>
        /// <returns>视图</returns>
        public ActionResult OfficeItemPurchaseApplyListPartial()
        {
            int pageIndex = Request.Params["pageIndex"] == null ? 0 : int.Parse(Request.Params["pageIndex"].ToString());
            int pageCount = Request.Params["PageCount"] == null ? 0 : int.Parse(Request.Params["PageCount"].ToString());
            int pageRowSize = Request.Params["pageRowSize"] == null ? 0 : int.Parse(Request.Params["pageRowSize"].ToString());
            int pageRowCount = Request.Params["pageRowCount"] == null ? 0 : int.Parse(Request.Params["pageRowCount"].ToString());
            string callbackArg = DevExpressHelper.CallbackArgument;
            string command = Request.Params["command"] == null ? "" : Request.Params["command"].ToString();
            string query = Request.Params["query"] == null ? "" : Request.Params["query"].ToString();
            if (command == "PAGERONCLICK")
            {
                string[] args = callbackArg.Split(new char[1] { '|' });
                string arg = args[args.Count() - 1];

                switch (arg)
                {
                    case "PBN;":
                        {
                            //下一页
                            pageIndex = pageIndex + 2;
                            break;
                        }
                    case "PBP;":
                        {
                            //上一页
                            //pageIndex = pageIndex;
                            break;
                        }
                    case "PBL;":
                        {
                            //最后一页
                            pageIndex = pageCount;
                            break;
                        }
                    case "PBF;":
                        {
                            //第一页
                            pageIndex = 1;
                            break;
                        }
                    default:
                        {
                            //点击数字页码
                            string tempIndex = arg.Replace("PN", "");
                            tempIndex = tempIndex.Replace(";", "");
                            if (RegExp.IsNumeric(tempIndex))
                            {
                                pageIndex = int.Parse(tempIndex) + 1;
                            }
                            break;
                        }

                }
            }
            else
            {
                pageIndex = pageIndex + 1;
            }

            List<Model.ItemPurchaseApply> itemPurchaseApplyList = GetItemPurchaseApplyList(pageIndex, pageCount, pageRowSize);


            return PartialView("OfficeItemPurchaseApplyListPartial", itemPurchaseApplyList);
        
        }


        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageCount">每页显示大小</param>
        /// <param name="pageRowSize">每页显示页数</param>
        /// <returns>广告集合</returns>
        private List<Model.ItemPurchaseApply> GetItemPurchaseApplyList(int pageIndex, int pageCount = 0, int pageRowSize = 0)
        {
            BLL.ItemPurchaseApply itemPurchaseApplyBll = new BLL.ItemPurchaseApply();

            BLL.Common commonBll = new BLL.Common();
            string fiedls = "*";
            int total;
            DataSet ds = commonBll.GetListByPage("dbo.v_ItemPurchaseApply_vEmplDept", fiedls, Common.GlobalConstant.CONSTRING_PAGESIZE, pageIndex,"", "FItemPurchaseApplyID", 0, out total);

            List<Model.ItemPurchaseApply> itemPurchaseApplyAllList = new List<Model.ItemPurchaseApply>();
            List<Model.ItemPurchaseApply> itemPurchaseApplyList = itemPurchaseApplyBll.DataTableToListItemPurchaseApply(ds.Tables[0]);

            pageRowSize = Common.GlobalConstant.CONSTRING_PAGESIZE;
            for (int i = 0; i < total; i++)
            {
                itemPurchaseApplyAllList.Add(null);
            }
            for (int i = 0; i < pageRowSize; i++)
            {
                if (itemPurchaseApplyList.Count > i)
                {
                    itemPurchaseApplyAllList[((pageIndex - 1) * pageRowSize) + i] = itemPurchaseApplyList[i];
                }
            }

            return itemPurchaseApplyAllList;
        }


        /// <summary>
        /// 页面初始化
        /// </summary>
        /// <param name="itemPurchaseApplyID">主键编号</param>
        /// <returns>视图</returns>
        public ActionResult OfficeItemPurchaseApplyEdit(string itemPurchaseApplyID)
        {
            Model.ItemPurchaseApply itemPurchaseApplyModel = new Model.ItemPurchaseApply();

            string emplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
            string deptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
            string entityNo = GlobalConstant.ENTITYNO;
            int z = 0;

            BLL.ItemPurchaseApply itemPurchaseApplyBll = new BLL.ItemPurchaseApply();
            if (string.IsNullOrEmpty(itemPurchaseApplyID))
            {           
                itemPurchaseApplyModel.FApplyDate = DateTime.Now;
                itemPurchaseApplyModel.FApplyDeptNo = deptNo;
                itemPurchaseApplyModel.FApplyEmplNo = emplNo;
                ViewData["type"] = "ADD";
            }
            else
            {
                itemPurchaseApplyModel = itemPurchaseApplyBll.GetModel(decimal.Parse(itemPurchaseApplyID));
                ViewData["type"] = "Edit";
                ViewData["id"] = itemPurchaseApplyID;
                BLL.ItemPurchaseApplyEntry entryBll = new BLL.ItemPurchaseApplyEntry();
                List<Model.ItemPurchaseApplyEntry> entryModelList = entryBll.GetListEntry(int.Parse(itemPurchaseApplyID));
                BLL.Item itemBll = new BLL.Item();
                foreach (Model.ItemPurchaseApplyEntry model in entryModelList)
                {                   
                    model.StrFRequestDate = model.FRequestDate.ToString("yyyy-MM-dd");
                }
                string json = "";
                if (entryModelList.Count > 0)
                {
                    json = JsonConvert.SerializeObject(entryModelList);
                }
                ViewData["json"] = json;
            }

            ///获取部门名称
            BLL.HRDept deptBll = new BLL.HRDept();
            string deptName = deptBll.GetDeptName(entityNo, deptNo);
            List<SelectListItem> itemDeptNameList = new List<SelectListItem>();
            itemDeptNameList.Add(new SelectListItem() { Text = deptName, Value = deptNo });
            ViewData["dept"] = itemDeptNameList;

            ///获得人员名称
            BLL.HREmpl emplBll = new BLL.HREmpl();
            string emplName = emplBll.GetEmpName(entityNo, emplNo);
            itemDeptNameList = new List<SelectListItem>();
            itemDeptNameList.Add(new SelectListItem() { Text = emplName, Value = emplNo });
            ViewData["empl"] = itemDeptNameList;


            return View(itemPurchaseApplyModel);
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="itemPurchaseApplyModel"></param>
        /// <returns></returns>
        public ActionResult Save(Model.ItemPurchaseApply itemPurchaseApplyModel)
        {

            string entityNo = GlobalConstant.ENTITYNO;
            string entryModel = Fetch.Post("hdresult");

            List<Model.ItemPurchaseApplyEntry> entryModelList = new List<Model.ItemPurchaseApplyEntry>();

            if (entryModel != "")
            {
                entryModelList = JsonConvert.DeserializeObject<List<Model.ItemPurchaseApplyEntry>>(entryModel);
            }
          
            BLL.ItemPurchaseApply itemPurchaseApply = new BLL.ItemPurchaseApply();

            string type = Fetch.Post("hdtype");        
            try 
            {
                if (type == "ADD")
                {
                    itemPurchaseApplyModel.FItemPurchaseApplyID = itemPurchaseApplyModel.FItemPurchaseApplyID;
                    itemPurchaseApplyModel.FEntityNo = entityNo;
                    itemPurchaseApplyModel.FApplyDeptNo = ComboBoxExtension.GetValue<string>("FApplyDeptNo");
                    itemPurchaseApplyModel.FApplyEmplNo = ComboBoxExtension.GetValue<string>("FApplyEmplNo");
                    itemPurchaseApplyModel.FApplyDate = DateTime.Parse(Fetch.Post("FApplyDate"));
                    itemPurchaseApplyModel.FApplyReason = Fetch.Post("FApplyReason");
                    itemPurchaseApplyModel.FApplyIP = GenerateUtil.GetClientIPv4Address();
                    itemPurchaseApplyModel.FStatus = "N";
                    itemPurchaseApplyModel.FUpdDate = DateTime.Now;
                    itemPurchaseApplyModel.FUpdEmplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                    itemPurchaseApplyModel.FUpdIP = GenerateUtil.GetClientIPv4Address();

                    itemPurchaseApply.Add(itemPurchaseApplyModel, entryModelList);
                    Response.Write("<script>alert('增加保存成功');window.location.href='" + Url.Action("OfficeItemPurchaseApplyList", "OfficeItemPurchaseApply") + "'</script>");
                    Response.Flush();
                    Response.End();
                }
                else if (type == "Edit")
                {
                    itemPurchaseApplyModel.FItemPurchaseApplyID = decimal.Parse(Fetch.Post("hdID"));
                    itemPurchaseApplyModel.FApplyReason = Fetch.Post("FApplyReason");
                    itemPurchaseApplyModel.FUpdDate = DateTime.Now;
                    itemPurchaseApplyModel.FUpdEmplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                    itemPurchaseApplyModel.FUpdIP = GenerateUtil.GetClientIPv4Address();

                    itemPurchaseApply.Update(itemPurchaseApplyModel, entryModelList);

                    Response.Write("<script>alert('增加保存成功');window.location.href='" + Url.Action("OfficeItemPurchaseApplyList", "OfficeItemPurchaseApply") + "'</script>");
                    Response.Flush();
                    Response.End();

                }

            }
            catch (Exception)
            {
                Response.Write("<script>alert('操作失败');window.location.href='" + Url.Action("OfficeItemPurchaseApplyList", "OfficeItemPurchaseApply") + "'</script>");
                Response.Flush();
                Response.End();
            }
            ViewData["id"] = Fetch.Post("hdID");
            return View("OfficeItemPurchaseApplyEdit", itemPurchaseApplyModel);
        }

        ///// <summary>
        ///// 得到具体明细
        ///// </summary>
        ///// <param name="entityNo">公司编号</param>
        ///// <returns></returns>
        //public List<Model.ItemPurchaseApplyEntry> GetEntryList(string entryModelList)
        //{

        //    List<Model.ItemPurchaseApplyEntry> entryModelList1 = new List<Model.ItemPurchaseApplyEntry>();
        //    if (entryModelList != "")
        //    {
        //        entryModelList1 = JsonConvert.DeserializeObject<List<Model.ItemPurchaseApplyEntry>>(entryModelList);
        //    }

        //    return entryModelList1;
            
        //}


        ///// <summary>
        ///// 用品的具体信息
        ///// </summary>
        ///// <param name="itemNo">用品编号</param>
        ///// <returns>视图</returns>
        //public ActionResult OfficeItemPurchaseApplyAddEntryInfo(string itemNo)
        //{
        //    Model.Item itemModel = new Model.Item();
        //    BLL.Item itemBll = new BLL.Item();
        //    string entityNo = GlobalConstant.ENTITYNO;

        //    itemModel = itemBll.GetModel(itemNo, entityNo);


        //    return View(itemModel);
        //}


        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="itemPurchaseApplyID">编号ID</param>       
        /// <returns>返回的字符串判断是否删除</returns>
        public string OfficeItemPurchaseApplyDel(string itemPurchaseApplyID)
        {
            string str = "";
            itemPurchaseApplyID = Fetch.estimateString(itemPurchaseApplyID, CheckGetEnum.Safety);
            BLL.ItemPurchaseApply itemPurchaseApplyBll = new BLL.ItemPurchaseApply();
            
            try
            {
                itemPurchaseApplyBll.Delete(decimal.Parse(itemPurchaseApplyID));
                str = "ok";
                
            }
            catch (Exception)
            {
                str = "error";
            
            }
            
            return str;
        }


        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="itemPurchaseApplyIDs">编号ID组</param>
        /// <returns>返回的字符串判断是否删除</returns>
        public string OfficeItemPurchaseApplyManyDel(string itemPurchaseApplyIDs)
        {
            string str = "";

            string[] itemPurchaseApplyIDArray = itemPurchaseApplyIDs.Split(new string[] { "%!^" }, StringSplitOptions.RemoveEmptyEntries);

            BLL.ItemPurchaseApply itemPurchaseApplyBll = new BLL.ItemPurchaseApply();
            try
            {
                itemPurchaseApplyBll.ManyDelete(itemPurchaseApplyIDArray);
                str = "ok";

            }
            catch (Exception)
            {
                str = "error";
            }


            return str;
        }

        /// <summary>
        /// 返回物品名称
        /// </summary>
        /// <param name="message">返回的信息</param>
        /// <returns>返回的字符串</returns>
        public string OfficeItemPurchaseApplyAddEntry(string message)
        {
            string str = "";
            BLL.Item itemBll = new BLL.Item();
            List<Model.Item> itemModelList = itemBll.GetModelList(message);

            str += JsonConvert.SerializeObject(itemModelList);

            return str;
        
        }

    }
}
